package com.xishu.service;

import com.xishu.annotation.lang.Lang;
import com.xishu.util.ClassUtil;
import com.xishu.util.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 国际化处理
 */
public class ZhEnService implements Tools {
    private static Logger logger = LoggerFactory.getLogger(ZhEnService.class);
    private static ZhEnService instance = new ZhEnService();

    private ZhEnService() {
    }

    public static ZhEnService getInstance() {
        return instance;
    }

    /**
     * 国际化处理，只要有一个有值，就把其它值都加入进来
     *
     * @param t
     * @param <T>
     */
    public <T> void dealZhEn(T t) throws IllegalAccessException {
        List<Field> fieldList = ClassUtil.getAllField(t.getClass()).stream().filter(f -> f.getAnnotation(Lang.class) != null).collect(Collectors.toList());

        for (Field field : fieldList) {
            field.setAccessible(true);
        }

        Map<String, List<Field>> groupList = fieldList.stream().collect(Collectors.groupingBy(f -> {
            Lang annotation = f.getAnnotation(Lang.class);
            return annotation.key();
        }));

        for (Map.Entry<String, List<Field>> listEntry : groupList.entrySet()) {
            List<Field> groupFieldList = listEntry.getValue();

            String name = null;

            //如果中英文都有了，就不再处理了
            List<Field> langFields = groupFieldList.stream().filter(f -> {
                Lang annotation = f.getAnnotation(Lang.class);
                return "zh".equalsIgnoreCase(annotation.lang()) || "en".equalsIgnoreCase(annotation.lang());
            }).collect(Collectors.toList());

            if (!langFields.isEmpty()) {
                boolean allMatch = langFields.stream().allMatch(f -> {
                    try {
                        return f.get(t) != null;
                    } catch (Exception e) {
                        //有问题时，不做国际化同步
                        logger.info("e", e);
                        return true;
                    }
                });

                if (allMatch) {
                    return;
                }
            }

            for (Field field : groupFieldList) {
                if (field.get(t) != null && isNotEmpty(field.get(t).toString())) {
                    name = field.get(t).toString();
                    break;
                }
            }

            for (Field field : groupFieldList) {
                field.set(t, name);
            }
        }
    }

    /**
     * 将请求里面为空的值，从数据库里面填写上
     *
     * @param t
     * @param tInDb
     * @param <T>
     */
    public <T> void updateSyncZhEn(T t, T tInDb) throws IllegalAccessException {
        List<Field> fieldList = ClassUtil.getAllField(t.getClass()).stream().filter(f -> f.getAnnotation(Lang.class) != null).collect(Collectors.toList());

        for (Field field : fieldList) {
            field.setAccessible(true);

            if (field.get(t) == null || isEmpty(field.get(t).toString())) {
                field.set(t, field.get(tInDb));
            }
        }
    }

    /**
     * 只有一个字段有值时的同步操作
     *
     * @param t
     * @param <T>
     */
    public <T> void syncZhEn(T t) throws IllegalAccessException {
        List<Field> fieldList = ClassUtil.getAllField(t.getClass()).stream().filter(f -> f.getAnnotation(Lang.class) != null).collect(Collectors.toList());

        for (Field field : fieldList) {
            field.setAccessible(true);
        }

        Map<String, List<Field>> groupList = fieldList.stream().collect(Collectors.groupingBy(f -> {
            Lang annotation = f.getAnnotation(Lang.class);
            return annotation.key();
        }));

        for (Map.Entry<String, List<Field>> listEntry : groupList.entrySet()) {
            List<Field> groupFieldList = listEntry.getValue();

            int okCount = 0;
            for (Field field : groupFieldList) {
                if (field.get(t) != null && isNotEmpty(field.get(t).toString())) {
                    okCount++;
                }
            }

            //不只一个，那么不用处理,下一组
            if (okCount > 1) {
                continue;
            }

            //这里肯定只能最多找到一个
            String name = null;
            for (Field field : groupFieldList) {
                if (field.get(t) != null && isNotEmpty(field.get(t).toString())) {
                    name = field.get(t).toString();
                    break;
                }
            }

            for (Field field : groupFieldList) {
                field.set(t, name);
            }
        }
    }
}
